$(document).ready(function () {
    var currentDate = new Date();
    var currentYear = currentDate.getFullYear();
    var currentMonth = currentDate.getMonth();
    var selectedDate = currentDate.getDate();
    updateCalendar(currentYear, currentMonth);
    displayPlans(currentDate);

    $(".add-plan").click(function(e){
        $('.popup-container').css('display','flex')
    })

    // 关闭弹窗
    $('.popup-container .close').click(function () {
        $('.popup-container').hide()
    });

    // 关闭弹窗
    $('.popup-container1 .close').click(function () {
        $('.popup-container1').hide()
    });

    // 切换到上一个月
    $('#prevMonth').on('click', function () {
        currentMonth--;
        if (currentMonth < 0) {
            currentMonth = 11;
            currentYear--;
        }
        updateCalendar(currentYear, currentMonth);
    });

    // 切换到下一个月
    $('#nextMonth').on('click', function () {
        currentMonth++;
        if (currentMonth > 11) {
            currentMonth = 0;
            currentYear++;
        }
        updateCalendar(currentYear, currentMonth);
    });

    // 当日日期高亮显示，并显示计划
    $('#calendarBody').on('click', 'td', function () {
        selectedDate = $(this).text();
        $('.calendar td').removeClass('today');
        $(this).addClass('today');
        var selectedDateTime = new Date(currentYear, currentMonth, selectedDate);
        displayPlans(selectedDateTime);
    });

    // 添加
    $('.save-plan').on('click', function (e) {
        e.preventDefault();
        var planTitle = $('#planTitle').val();
        var planDescription = $('#planDescription').val();
        var planCompleted = $('#planCompleted').prop('checked');

        //校验
        if (planTitle === '') {
            $.fn.msg({
                content: '请输入计划标题！',
                type: 'error'
            });
            return;
        }
        if (planDescription === '') {
            $.fn.msg({
                content: '请输入计划描述！',
                type: 'error'
            });
            return;
        }
        


        // 解析当前日期，用于构建planKey
        var currentDate = new Date();
        var currentYear = currentDate.getFullYear();
        var currentMonth = currentDate.getMonth(); // 注意月份是从0开始的，所以需要+1
        var selectedDate = currentDate.getDate();
        // 获取时分秒
        var currentHour = currentDate.getHours();
        var currentMinute = currentDate.getMinutes();
        var currentSecond = currentDate.getSeconds();


        // 使用padStart补零
        currentMonth = (currentMonth + 1).toString().padStart(2, '0');
        selectedDate = selectedDate.toString().padStart(2, '0');

       
        var planKey =  $("#currentMonthYear").text()+'-'+padZero($("#calendarBody td.today").text());

        var planDateTime = currentYear + '-' + currentMonth + '-' + selectedDate + ' ' + padZero(currentHour) + ':' + padZero(currentMinute) + ':' + padZero(currentSecond);

        var planData = {
            title: planTitle,
            description: planDescription,
            dateTime: planDateTime,
            completed: planCompleted
        };

        var plans = JSON.parse(localStorage.getItem(planKey)) || [];
        plans.push(planData);
        localStorage.setItem(planKey, JSON.stringify(plans));

        displayPlans(new Date(planKey)); // 注意月份要减去1，因为月份是从0开始的
        // $('#planForm')[0].reset();
        $('.popup-container').hide()
        $('#planTitle').val('')
        $('#planDescription').val('')
        $.fn.msg({
            content: '保存成功',
            type: 'success'
        });
    });

    // 补零函数
    function padZero(num) {
        return (num < 10 ? '0' : '') + num;
    }

    // 更新日期
    function updateCalendar(year, month) {
        $('#currentMonthYear').text(year + '-' + padZero(month + 1));
        var firstDay = new Date(year, month, 1).getDay();
        var daysInMonth = new Date(year, month + 1, 0).getDate();
        var calendarBody = $('#calendarBody');
        calendarBody.empty();
        var date = 1;
        for (var i = 0; i < 6; i++) {
            var row = $('<tr></tr>');
            for (var j = 0; j < 7; j++) {
                if (i === 0 && j < firstDay) {
                    row.append($('<td></td>'));
                } else if (date > daysInMonth) {
                    break;
                } else {
                    var cell = $('<td></td>').text(date);
                    if (year === currentDate.getFullYear() && month === currentDate.getMonth() && date === currentDate.getDate()) {
                        cell.addClass('today');
                    }
                    row.append(cell);
                    date++;
                }
            }
            calendarBody.append(row);
        }
    }

    function formatDateTime(dateTimeString) {
        const date = new Date(dateTimeString);
        const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' };
        return date.toLocaleString('zh-CN', options); // 返回类似 "2024年04月02日, 19:54" 的格式
    }

    // 显示指定日期的计划
    function displayPlans(date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1).toString().padStart(2, '0');
        var day = date.getDate().toString().padStart(2, '0');
        var planKey = year + '-' + month + '-' + day;
        var plans = JSON.parse(localStorage.getItem(planKey)) || [];
        $('#selectedDate').text(date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate());
        var planList = $('#planList').empty();
        var totalPlans = 0;
        var completedPlans = 0;
        plans.forEach(function (plan, index) {
            totalPlans++;
            // 为每个计划项创建一个唯一的ID
            var planItemId = 'plan-item-' + index;
            var planItem = $(`<div class="plan-item" id="${planItemId}"></div>`).append(
                `<input class="checkbox" type="checkbox" ${plan.completed ? 'checked' : ''} data-plan-index="${index}" data-plan-date="${planKey}">`,
                `<div><h3 class="title">${plan.title}</h3><p class="description">${plan.description}</p></div>`,
                `<p class="dateTime">${formatDateTime(plan.dateTime)}</p>`,
                `<button class="deletePlan" data-index="${index}">删除</button>`
            );
            if (plan.completed) {
                planItem.addClass('completed-plan');
            } else {
                planItem.removeClass('completed-plan');
            }
            planList.append(planItem);
        });
        $('#totalPlans').text(totalPlans);
        // 如果计划已完成，增加已完成的计划数
        var completedPlans = countCompletedPlans(plans)
        $('#completedPlans').text(completedPlans);
        $('#progress-bar-inner').css('width', (completedPlans / totalPlans) * 100 + '%');

        if (totalPlans == 0) {
            $('#progress-bar-inner').css('width', '0%');
            $(".data-no").show()
            $("#planList").hide()
        } else {
            $(".data-no").hide()
            $("#planList").show()
            $('#progress-bar-inner').css('width', (completedPlans / totalPlans) * 100 + '%');
        }

    }


    // 为checkbox添加事件监听器
    $(document).on('change', '.plan-item input[type="checkbox"]', function () {
        var planItem = $(this);
        var date = new Date(planItem.attr('data-plan-date'));
        var year = date.getFullYear();
        var month = (date.getMonth() + 1).toString().padStart(2, '0');
        var day = date.getDate().toString().padStart(2, '0');
        var planIndex = $(this).data('plan-index');
        var planDate = planItem.attr('datavar-plan-date');
        var isCompleted = $(this).is(':checked');
        var planItemId = planItem.attr('id');
        var planKey = year + '-' + month + '-' + day;
        var plans = JSON.parse(localStorage.getItem(planKey)) || [];

        // 更新localStorage中的计划状态
        var updatedPlans = plans.map(function (p, idx) {
            if (idx === planIndex) {
                return {
                    ...p,
                    completed: isCompleted
                };
            }
            return p;
        });

        localStorage.setItem(planKey, JSON.stringify(updatedPlans));
        // 使用正确的日期对象调用displayPlans
        displayPlans(date);
    });

    function countCompletedPlans(plans) {
        return plans.filter(plan => plan.completed).length;
    }

    // 删除
    $('#planList').on('click', '.deletePlan', function () {
        let _this = this;
        // 显示确认对话框
        $.fn.confirmMsg({
            title: '删除',
            content: '确定要执行此操作吗？',
            confirmCallback: function () {
                var index = $(_this).data('index');
                var planKey =  $("#currentMonthYear").text()+'-'+padZero($("#calendarBody td.today").text());

                var plans = JSON.parse(localStorage.getItem(planKey)) || [];

                plans.splice(index, 1); // 从数组中删除指定的计划
                localStorage.setItem(planKey, JSON.stringify(plans)); // 更新localStorage
        
                displayPlans(new Date(planKey)); // 重新显示计划列表
        
                var completedPlans = countCompletedPlans(plans)
                var totalPlans = $(".plan-item").length;
                if (totalPlans == 0) {
                    $('#progress-bar-inner').css('width', '0%');
                    $(".data-no").show()
                } else {
                    $(".data-no").hide()
                    $('#progress-bar-inner').css('width', (completedPlans / totalPlans) * 100 + '%');
                }
            },
            cancelCallback: function () {
                console.log('点击了取消按钮');
                // 这里可以编写取消按钮点击后执行的操作
            }
        });
       
    });
});